from django.contrib.auth.models import AbstractUser
from django.db import models


# Create your models here.

class Authority(models.Model):
    """
    权限表
    """
    title = models.CharField(max_length=32, verbose_name='权限名称')
    type = models.CharField(max_length=32, verbose_name='资源类型', choices=[("menu", "菜单权限"), ("button", "按钮权限")])
    url = models.CharField(max_length=128, verbose_name='访问url地址', null=True, blank=True)
    code = models.CharField(max_length=32, verbose_name='权限代码字符', null=True, blank=True)
    pid = models.ForeignKey("Authority", on_delete=models.CASCADE, null=True, verbose_name='父权限', blank=True)
    levels = models.CharField(max_length=32, null=True, blank=True, verbose_name="权限层级")  # "1/5/13" 可避开递归,当然需要重写save

    class Meta:
        verbose_name_plural = '权限表'
        verbose_name = '权限表'
        ordering = ["title"]

    def __str__(self):
        return "%s(%s)" % (self.title, self.get_type_display())


class Role(models.Model):
    name = models.CharField(max_length=32, verbose_name='角色名称')
    type = models.IntegerField(verbose_name="角色类型", choices=[(1, "超级用户"), (2, "管理员"), (3, "普通用户")])
    authority = models.ManyToManyField(to='Authority', verbose_name='角色所拥有的权限', blank=True, db_constraint=False)

    def __str__(self):
        return "%s(%s)" % (self.name, self.get_type_display())

    class Meta:
        verbose_name_plural = '角色表'
        verbose_name = '角色表'
        ordering = ["name"]


class User(AbstractUser):
    """
    用户表
    """
    roles = models.ManyToManyField(to=Role, verbose_name='用户所拥有的角色', blank=True, db_constraint=False)

    def __str__(self):
        return self.username

    class Meta:
        abstract = True
